package gui.engraving;

import javax.swing.JPanel;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import entities.Employee;
import entities.EngraveComment;
import entities.ProductionOrder;

import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JComboBox;

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.SwingConstants;

import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.TextField;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import javax.swing.DefaultComboBoxModel;

import utilities.Services;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;

import net.miginfocom.swing.MigLayout;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.ImageIcon;

import java.awt.SystemColor;
import java.awt.Font;

/**
 * @author Idan
 *This is the seperation step GUI
 */
public class EngravingSeperatePanel extends JPanel
{
	public JTextField orderIDTextField;
	private JTextField typeTextField;
	private JTextField diopterTextField;
	private JTextField quantityTextField;
	private JTextField sideATextField;
	private JTextField sideBTextField;
	private EngravingPanel myPanel;
	private ArrayList<Object> listOfEmployees = new ArrayList<Object>();
	private JComboBox employeeComboBox;
	private JComboBox shiftComboBox;
	private JTextField dateTextField;
	private Date todayCalendar;
	private String today;
	private final DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
	private JButton seperateButton;
	//private Border defaultTextFieldBorder;
	//private Border defaultComboBoxBorder;
		
	public EngravingSeperatePanel(EngravingPanel engravingPanel)
	{
		setBackground(new Color(173, 216, 230));
		this.myPanel = engravingPanel;
		todayCalendar = Calendar.getInstance().getTime();
		today = dateFormat.format(todayCalendar);
		
		setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,},
			new RowSpec[] {
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,}));
		
		JPanel panel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		panel.setBackground(new Color(173, 216, 230));
		panel.setBorder(new TitledBorder(null, "\u05D3\u05D5\u05D7 \u05D4\u05E4\u05E8\u05D3\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		add(panel, "6, 4, center, center");
		
		orderIDTextField = new JTextField();
		orderIDTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		orderIDTextField.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				// Assume Enter was pressed
				String order = orderIDTextField.getText();
				if (order.length() > 7)
				{
					order = order.substring(3); // remove the first 3 characters
					orderIDTextField.setText(order);
				}
				employeeComboBox.requestFocus();
				
			}
		});
		orderIDTextField.addFocusListener(new FocusAdapter()
		{
			@Override
			public void focusLost(FocusEvent arg0) 
			{
				//Assume OrderID was typed, try and get order data from DB.
				if (orderIDTextField.getText().equals(""))
				{
					// Field is empty, do nothing.
				}
				else
				{
					
						getOrderData(orderIDTextField.getText());
					
				}
				
				
			}
		});
		panel.setLayout(new MigLayout("", "[127px][35px][::100px][48px][1px:n][117px][61px]", "[28px][28px][220px]"));
		
		diopterTextField = new JTextField();
		diopterTextField.setEditable(false);
		diopterTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		diopterTextField.setBackground(Color.LIGHT_GRAY);
		panel.add(diopterTextField, "cell 0 0,alignx right");
		diopterTextField.setColumns(8);
		
		JLabel diopterLabel = new JLabel("דיופטר:");
		diopterLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(diopterLabel, "cell 1 0,alignx right,aligny center");
		
		typeTextField = new JTextField();
		typeTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		typeTextField.setEditable(false);
		typeTextField.setHorizontalAlignment(SwingConstants.LEFT);
		typeTextField.setBackground(Color.LIGHT_GRAY);
		panel.add(typeTextField, "cell 2 0,alignx center");
		typeTextField.setColumns(8);
		
		JLabel typeLabel = new JLabel("סוג עדשה:");
		typeLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(typeLabel, "cell 3 0,alignx left,aligny center");
		orderIDTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		panel.add(orderIDTextField, "cell 5 0,alignx right,aligny top");
		orderIDTextField.setColumns(8);
		
		JLabel orderIDLabel = new JLabel("פק\"ע:");
		orderIDLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(orderIDLabel, "cell 6 0,growx,aligny center");
		
		sideBTextField = new JTextField();
		sideBTextField.setEditable(false);
		sideBTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		sideBTextField.setBackground(Color.LIGHT_GRAY);
		panel.add(sideBTextField, "cell 0 1,alignx right");
		sideBTextField.setColumns(3);
		
		JLabel sideBLabel = new JLabel("צד 2:");
		sideBLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(sideBLabel, "cell 1 1,alignx right,aligny center");
		
		sideATextField = new JTextField();
		sideATextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		sideATextField.setEditable(false);
		sideATextField.setHorizontalAlignment(SwingConstants.RIGHT);
		sideATextField.setBackground(Color.LIGHT_GRAY);
		panel.add(sideATextField, "cell 2 1,alignx right");
		sideATextField.setColumns(3);
		
		JLabel sideALabel = new JLabel("צד 1:");
		sideALabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(sideALabel, "cell 3 1,alignx right,aligny center");
		
		quantityTextField = new JTextField();
		quantityTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		quantityTextField.setText("0");
		quantityTextField.setEditable(false);
		quantityTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		quantityTextField.setBackground(Color.LIGHT_GRAY);
		panel.add(quantityTextField, "cell 5 1,alignx right,aligny top");
		quantityTextField.setColumns(3);
		
		JLabel quantityLabel = new JLabel("כמות בפק\"ע:");
		quantityLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		panel.add(quantityLabel, "cell 6 1,alignx left,aligny center");
		
		JPanel innerPanel = new JPanel(){@Override
			public void paintComponent(Graphics g) {
	        Graphics2D g2d = (Graphics2D) g;
	        Color color1 = getBackground();
	        Color color2 = color1.darker();
	        int w = getWidth();
	        int h = getHeight(); 
	        GradientPaint gp = new GradientPaint(
	                0, 0, color1,
	                0, h, color2);

	        g2d.setPaint(gp);
	        g2d.fillRect(0, 0, w, h);
	        }};
		innerPanel.setBackground(new Color(173, 216, 230));
		innerPanel.setBorder(new TitledBorder(null, "\u05E4\u05E8\u05D8\u05D9 \u05D4\u05E4\u05E8\u05D3\u05D4", TitledBorder.RIGHT, TitledBorder.TOP, null, null));
		panel.add(innerPanel, "cell 0 2 3 1,alignx center,growy");
		GridBagLayout gbl_innerPanel = new GridBagLayout();
		gbl_innerPanel.columnWidths = new int[]{40, 88, 39, 88, 33, 0};
		gbl_innerPanel.rowHeights = new int[]{37, 28, 26, 0};
		gbl_innerPanel.columnWeights = new double[]{0.0, 1.0, 0.0, 1.0, 0.0, Double.MIN_VALUE};
		gbl_innerPanel.rowWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
		innerPanel.setLayout(gbl_innerPanel);
		
		dateTextField = new JTextField();
		dateTextField.setFont(new Font("Tahoma", Font.PLAIN, 13));
		dateTextField.setEditable(false);
		GridBagConstraints gbc_dateTextField = new GridBagConstraints();
		gbc_dateTextField.anchor = GridBagConstraints.NORTH;
		gbc_dateTextField.fill = GridBagConstraints.HORIZONTAL;
		gbc_dateTextField.insets = new Insets(0, 0, 5, 5);
		gbc_dateTextField.gridx = 3;
		gbc_dateTextField.gridy = 1;
		innerPanel.add(dateTextField, gbc_dateTextField);
		dateTextField.setHorizontalAlignment(SwingConstants.RIGHT);
		dateTextField.setBackground(Color.LIGHT_GRAY);
		dateTextField.setColumns(10);
		
		JLabel dateLabel = new JLabel("תאריך:");
		dateLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		GridBagConstraints gbc_dateLabel = new GridBagConstraints();
		gbc_dateLabel.anchor = GridBagConstraints.WEST;
		gbc_dateLabel.insets = new Insets(0, 0, 5, 0);
		gbc_dateLabel.gridx = 4;
		gbc_dateLabel.gridy = 1;
		innerPanel.add(dateLabel, gbc_dateLabel);
		
		shiftComboBox = new JComboBox();
		shiftComboBox.setFont(new Font("Tahoma", Font.PLAIN, 13));
		shiftComboBox.setModel(new DefaultComboBoxModel(new String[] {"בוקר", "ערב"}));
		((JLabel)shiftComboBox.getRenderer()).setHorizontalAlignment(JLabel.RIGHT);
		GridBagConstraints gbc_shiftComboBox = new GridBagConstraints();
		gbc_shiftComboBox.anchor = GridBagConstraints.NORTH;
		gbc_shiftComboBox.fill = GridBagConstraints.HORIZONTAL;
		gbc_shiftComboBox.insets = new Insets(0, 0, 0, 5);
		gbc_shiftComboBox.gridx = 1;
		gbc_shiftComboBox.gridy = 2;
		innerPanel.add(shiftComboBox, gbc_shiftComboBox);
		
		
		JLabel shiftLabel = new JLabel("משמרת:");
		shiftLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		GridBagConstraints gbc_shiftLabel = new GridBagConstraints();
		gbc_shiftLabel.anchor = GridBagConstraints.WEST;
		gbc_shiftLabel.insets = new Insets(0, 0, 0, 5);
		gbc_shiftLabel.gridx = 2;
		gbc_shiftLabel.gridy = 2;
		innerPanel.add(shiftLabel, gbc_shiftLabel);
		
		employeeComboBox = new JComboBox();
		employeeComboBox.setFont(new Font("Tahoma", Font.PLAIN, 13));
		employeeComboBox.setModel(new DefaultComboBoxModel(new String[] {""}));
		GridBagConstraints gbc_employeeComboBox = new GridBagConstraints();
		gbc_employeeComboBox.anchor = GridBagConstraints.NORTH;
		gbc_employeeComboBox.fill = GridBagConstraints.HORIZONTAL;
		gbc_employeeComboBox.insets = new Insets(0, 0, 0, 5);
		gbc_employeeComboBox.gridx = 3;
		gbc_employeeComboBox.gridy = 2;
		innerPanel.add(employeeComboBox, gbc_employeeComboBox);
		
		JLabel employeeLabel = new JLabel("מבצע:");
		employeeLabel.setFont(new Font("Tahoma", Font.PLAIN, 13));
		GridBagConstraints gbc_employeeLabel = new GridBagConstraints();
		gbc_employeeLabel.fill = GridBagConstraints.HORIZONTAL;
		gbc_employeeLabel.gridx = 4;
		gbc_employeeLabel.gridy = 2;
		innerPanel.add(employeeLabel, gbc_employeeLabel);
		
		seperateButton = new JButton("דווח על הפרדה");
		seperateButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		seperateButton.setIcon(new ImageIcon(EngravingSeperatePanel.class.getResource("/graphics/apply.png")));
		seperateButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) 
			{
				boolean isValid = checkIfEverythingIsValid();
				if (isValid)
					reportSeperation();	
				
				clearFields();
				
			}
		});
		panel.add(seperateButton, "cell 6 2,alignx center,aligny bottom");
		
		JButton btnNewButton = new JButton("יציאה");
		btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 13));
		btnNewButton.setIcon(new ImageIcon(EngravingSeperatePanel.class.getResource("/graphics/exit.png")));
		btnNewButton.addMouseListener(new MouseAdapter() 
		{
			@Override
			public void mouseClicked(MouseEvent e)
			{
				Object[] options = {"כן","לא"};
        		int n = JOptionPane.showOptionDialog(myPanel, "האם ברצונך לצאת מהמערכת?","אישור יציאה", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,"");
        		
        		if (n==0)
        		{
        			if (myPanel.engravingClient != null)
                    {
                      try
                      {
                    	  myPanel.engravingClient.close();
                      }
                      catch (Exception ignore)
                      {}
                     }
            		
            		System.exit(0);
        		}
			}
		});
		add(btnNewButton, "6, 6, center, center");
		//defaultTextFieldBorder = quantityTextField.getBorder();
		//defaultComboBoxBorder = employeeComboBox.getBorder();
		clearFields();
	}
	
	
	
	
	/**
	 * Gui variables initialization
	 */
	
	public void setVariables(ArrayList<Object> response)
	{
		// break the response array lists to local array lists.
		ArrayList<Object> localListOfEmpoyees = (ArrayList<Object>) response.get(1);		
		int employeeCounter = Integer.parseInt(localListOfEmpoyees.get(0).toString());
		listOfEmployees.add(employeeCounter);
		
		
		
		while (employeeCounter>0)
		{
			Employee employee = (Employee)localListOfEmpoyees.get(employeeCounter);
			listOfEmployees.add(employee);
			employeeComboBox.addItem(Services.createObject(employee.getEmployeeName()));
			employeeCounter--;
		}
		

			
	}





/**
 * Used to initializes the GUI after a report was made
 */
	public void initializeAfterReport(ProductionOrder newReport, ProductionOrder currentOrderID)
	{
		orderIDTextField.setText(String.valueOf(newReport.getOrderID()));
		typeTextField.setText(newReport.getType());
		diopterTextField.setText(String.valueOf(newReport.getDiopter()));
		quantityTextField.setText(String.valueOf(currentOrderID.getQuantity()));
		sideATextField.setText(String.valueOf(currentOrderID.getSideA() + newReport.getReportSideA()));
		sideBTextField.setText(String.valueOf(currentOrderID.getSideB() + newReport.getReportSideB()));
		dateTextField.setText(newReport.getEngraveDateAsString());
		employeeComboBox.setSelectedIndex(0);
		
		
		
		shiftComboBox.setSelectedIndex(newReport.getShift()-1);
	}
	
	/**
	 * Fetches order data from the server
	 */
	public void getOrderData(String orderID)
	{
		seperateButton.setEnabled(false);
		
		
	
		// Attempt to get order data from DBS
		ArrayList<Object> response = new ArrayList<Object>();
		ArrayList<Object> message = new ArrayList<Object>();
		
		if (Services.isNumeric(orderIDTextField.getText()))
			{
				
				message.add("getOrderIdData");
				message.add(orderID);
				

				
				try
				{
					response = myPanel.engravingClient.call(message);
					
					
					// handle data
					String mySQLReply = response.get(1).toString();
					
					if (mySQLReply.equalsIgnoreCase("valid"))
					{
						
						// Handle order data
					
						ProductionOrder order = (ProductionOrder)response.get(2);
						
						if (order.getStatusID()>2)
						{
							// Order report is already complete
							
							clearFields();
							
							JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
								    "כבר הופק דוח הפרדה עבור פק''ע זו.","שגיאה",JOptionPane.ERROR_MESSAGE);
							orderIDTextField.setText("");
							
						}
						else
						{
							// Display Data
							
							
							typeTextField.setText(order.getType());
							quantityTextField.setText(String.valueOf(order.getQuantity()));
							sideATextField.setText(String.valueOf(order.getSideA()));
							sideBTextField.setText(String.valueOf(order.getSideB()));
							diopterTextField.setText(String.valueOf(order.getDiopter()));							
							seperateButton.setEnabled(true);
				
						}
						
					}
					else
					{
						if (mySQLReply.equalsIgnoreCase("invalid"))
						{
							// Display no order was found error
							JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
								    "פק''ע לא נמצאה במערכת.","שגיאה",JOptionPane.ERROR_MESSAGE);
							clearFields();
						}
						else
							if(mySQLReply.equalsIgnoreCase("SQL Failed"))
							{
								// Display SQL Error
								JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
									    "שגיאה בבסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
						//		System.out.println("SQL Error");
							}
						
					}
					
					
				} catch (Exception e)
				{

					//e.printStackTrace();
				
				}
				
				
				
				
			}
		else
		{
			
			// not a valid orderID
				
			//	handleBorder(orderIDTextField, Color.red);
				JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
					    "יש להקליד מספר פק''ע תקין.","שגיאה",JOptionPane.ERROR_MESSAGE);
			clearFields();
		}
		
		
	}
	
	/**
	 * Clear all fields in the GUI
	 */
	
	public void clearFields() 
	{
		dateTextField.setText(today);
		typeTextField.setText("");
		sideATextField.setText("");
		sideBTextField.setText("");
		diopterTextField.setText("");
		sideATextField.setText("0");
		sideBTextField.setText("0");
		quantityTextField.setText("0");
		orderIDTextField.setText("");
		seperateButton.setEnabled(true);
		employeeComboBox.setSelectedIndex(0);
		shiftComboBox.setSelectedIndex(0);
		
	}
	
	/**
	 * Create a seperation report
	 */
	private void reportSeperation()
	{
		seperateButton.setEnabled(false);
		
		// build report entity
		ProductionOrder separationReport = new ProductionOrder();
		separationReport.setOrderID(Integer.parseInt(orderIDTextField.getText()));
		separationReport.setShift(shiftComboBox.getSelectedIndex()+1);
		// Use engraveDate as a "reportDate" variable to hold the separation date
		separationReport.setEngraveDateAsString(dateTextField.getText());
		String employeeID = (((Employee)(listOfEmployees.get(employeeComboBox.getSelectedIndex()))).getID());
	//	System.out.println("========" + employeeID);
		separationReport.setEmployeeID(employeeID);
		
		ArrayList<Object> message = new ArrayList<Object>();
		message.add("newSeparationReport");
		message.add(separationReport);
		
		//execute
		
		// Send to server
				try
				{
							
					ArrayList<Object> response = myPanel.engravingClient.call(message);
					
					if (response.get(0).toString().equalsIgnoreCase("Valid"))
					{
						JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
							    "דיווח על ההפרדה בוצע.","אישור",JOptionPane.INFORMATION_MESSAGE);
						myPanel.listOfReportsPanel.removeFromTable(orderIDTextField.getText());
						myPanel.setSelectedIndex(0);
					}
					else
					if (response.get(0).toString().equalsIgnoreCase("Failed in newSeparationReport"))
					{
						JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
							    "לא ניתן ליצור דו''ח עקב תקלה בתקשורת.","שגיאה",JOptionPane.ERROR_MESSAGE);
					}
					else
					{
						JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
							    "לא ניתן ליצור דו''ח עקב בעיה בבסיס הנתונים.","שגיאה",JOptionPane.ERROR_MESSAGE);
					}
				} 
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
		// clear fields
				clearFields();
		
	}

	/**
	 * Test input for validity
	 */
	private boolean checkIfEverythingIsValid() 
	{
		seperateButton.setEnabled(false);
		
		
		
		
		if (!Services.isNumeric(orderIDTextField.getText()) || orderIDTextField.getText().equals(""))
		{
			// not a valid orderID
			
		//	handleBorder(orderIDTextField, Color.red);
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש להקליד מספר פק''ע תקין.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		else
		if (!(sideATextField.getText().equals(sideBTextField.getText()) && sideATextField.getText().equals(quantityTextField.getText())) )
		{
						
			// quantities don't match
			
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "לא ניתן לבצע מכיוון שלא בוצע דיווח קודם.","שגיאה",JOptionPane.ERROR_MESSAGE);
			clearFields();
			return false;
		}
		else
		if (employeeComboBox.getSelectedIndex()==0)
		{
			// select an employee
			
		
			
			JOptionPane.showMessageDialog(myPanel.myEngravingFrame,
				    "יש לבחור שם עובד.","שגיאה",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
				
		seperateButton.setEnabled(true);
		return true;
	}
	@Override
	public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    Color color1 = getBackground();
    Color color2 = color1.darker();
    int w = getWidth();
    int h = getHeight(); 
    GradientPaint gp = new GradientPaint(
            0, 0, color1,
            0, h, color2);

    g2d.setPaint(gp);
    g2d.fillRect(0, 0, w, h);
    }
	
}
